﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using MySystemMag.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MySystemMag.DAL
{
    public class JWTService:IJWTService
    {
        private readonly IConfiguration _configuration;
        /// <summary>
        /// 在构造函数中注入configuration以拿取appsettings.json中的内容
        /// </summary>
        /// <param name="configuration"></param>
        public JWTService(IConfiguration configuration)
        {
            this._configuration = configuration;
        }

        public string GetToken(string UserID, string pass)
        {
            var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name,UserID),
                        new Claim("password",pass),
                        new Claim("time",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                    };
            //var jwtConfig = _configuration.GetSection("JwtSettings");
            var jwtSettings = new JwtSettings();
            _configuration.Bind("JwtSettings", jwtSettings);
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.SecretKey));
            //初始化签名凭证
            SigningCredentials creds = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                 issuer: jwtSettings.Issuer,//设置签发者
                 audience: jwtSettings.Audience,//设置接收者
                 claims: claims,//设置payload
                 expires: DateTime.Now.AddDays(1),//有效期1天
                 signingCredentials: creds);//初始化安全令牌参数
            //输出token
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }
    }
}
